<?php

namespace App\Http\Controllers\User;

use App\Events\Message;
use App\Http\Controllers\BaseController;
use App\Models\Ad;
use App\Models\Firm;
use App\Models\FirmBrand;
use App\Models\Gift;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Yansongda\Pay\Pay;

class GiftController extends BaseController
{
    public function index()
    {

    }

    public function store(Request $request)
    {
        $param = $this->validate($request,[
            'type' => 'required|in:1,2',
            'amount' => 'required',
            'firm_id' => 'required_if:type,1',
            'brand_id' => 'required_if:type,2',
            'pay_method' => 'required|in:1,2',
            'platform' => 'required|in:1,2,3',
        ]);

        if ($param['type']==1){
            $param['income_user_id'] = DB::table('firms')
                                ->where('id',$param['firm_id'])
                                ->value('user_id');
        }else{
            $param['income_user_id'] = DB::table('firm_brands')
                                ->where('id',$param['brand_id'])
                                ->value('user_id');
        }
        $user = auth('api')->user();
        $send_gift_share_profit = admin_setting_array('send_gift_share_profit');

        if ($send_gift_share_profit){
            $rate = array_sum(array_values($send_gift_share_profit));
            $param['user_income'] = bcmul((string)$param['amount'],bcdiv((string)(100-$rate),'100',2),2);
            if ($user['parent_id']){
                $param['parent_id'] = $user['parent_id'];
                $param['direct_distribution_income'] = bcmul((string)$param['amount'],(string)($send_gift_share_profit['direct_distribution_rate']/100),2);
                $grand_id = DB::table('users')->where('id',$user['paren_id'])->value('parent_id');
                if ($grand_id){
                    $param['grand_id'] = $grand_id;
                    $param['interposition_income'] =  bcmul((string)$param['amount'],(string)($send_gift_share_profit['direct_distribution_rate']/100),2);
                }
            }

        }

        $param['user_id']  = $user['id'];
        $param['giftable_id'] = $param['type']==1 ? $param['firm_id'] : $param['brand_id'];
        $param['giftable_type'] = $param['type']==1 ? Firm::class : FirmBrand::class;

        $param['order_no'] = getTradeNo();
        $gift =  Gift::query()->create($param);


        if ($gift->getKey()){
            $config = config('pay');
            switch ($param['pay_method']){
                case 1 :
                    $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/user/gift/notify';
                    Pay::config($config);
                    $order = [
                        'out_trade_no' => $gift->order_no,
                        'description' => '打赏支付',
                        'amount' => [
                            'total' => (int)bcmul($gift->amount,'100'),
                        ],
                    ];

                    $payInfo = '';
                    switch ($param['platform']){
                        case 1:
                            $payInfo =  Pay::wechat()->app($order);
                            break;
                        case 2 :
                            $order['payer']['openid'] = $user['wx_min_openid'];
                            $payInfo = Pay::wechat()->mini($order);
                            break;
                        case 3 :
                            $result = Pay::wechat()->scan($order);
                            $payInfo = ['code_url' => $result->code_url,'trade_no'=> $gift->order_no];
                            break;
                    }

                    return $this->success($payInfo);
                case 2 :
                    $config['alipay']['default']['notify_url'] = 'https://www.huashimu.com/api/user/gift/ali/notify';

                    if ($param['type']==1){
                        $config['alipay']['default']['return_url'] = 'http://www.xn--4pvs78ay6h.xn--fiqs8s/#/manage/manageDetail?id='.$param['firm_id'];
                    }else{
                        $config['alipay']['default']['return_url'] = 'http://www.xn--4pvs78ay6h.xn--fiqs8s/#/brand/brandDetail?id='.$param['brand_id'];
                    }

                    Pay::config($config);
                    if ($param['platform']==1){
                        $aliPay  = Pay::alipay()->app([
                            'out_trade_no' =>  $gift->order_no,
                            'total_amount' => $gift->amount,
                            'subject' => '打赏支付',
                        ])->getBody()->getContents();
                    }else{
                        $aliPay  = Pay::alipay()->web([
                            'out_trade_no' =>  $gift->order_no,
                            'total_amount' => $gift->amount,
                            'subject' => '打赏支付',
                        ])->getBody()->getContents();
                    }

                    return  $this->success(['payInfo' => $aliPay]);
            }

        }

        return  $this->error();


    }


    public function notify()
    {
        $config = config('pay');
        $config['wechat']['default']['notify_url'] = 'https://www.huashimu.com/api/user/gift/notify';
        Pay::config($config);

        $result = Pay::wechat()->callback();


        if ($result && $result['event_type'] == 'TRANSACTION.SUCCESS'){
            $order = Gift::query()->where('order_no',$result['resource']['ciphertext']['out_trade_no'])->first();

            if ($order && $order->status==0){
                $trade_time = date('Y-m-d H:i:s',strtotime($result['resource']['ciphertext']['success_time']));

                Gift::query()->where('id',$order->id)->update([
                    'status' => 1,
                    'pay_time' => $trade_time
                ]);

                DB::table('users')
                    ->where('id',$order->income_user_id)
                    ->increment('balance',$order->user_income);
                DB::table('user_balance_details')
                    ->insert([
                        'type' => 1,
                        'source_income_user_id' => $order->user_id,
                        'user_id' => $order->income_user_id,
                        'change_type' => 1,
                        'amount' => $order->user_income,
                        'remark' => '打赏收益',
                        'change_time' => date('Y-m-d H:i:s')
                    ]);


                event(new \App\Events\Message([
                    'user_id' =>  $order->user_id,
                    'type' => 3,
                    'content' => '你的打赏已支付成功,资金将会进入您打赏的企业或品牌,感谢您的支持!'
                ]));

                event(new Message([
                    'user_id' => $order->income_user_id,
                    'type' => 4,
                    'content' => '打赏余额收益已入账'
                ]));

                if ($order->parent_id && $order->direct_distribution_income>0){
                    DB::table('users')
                        ->where('id',$order->parent_id)
                        ->increment('balance',$order->direct_distribution_income);
                    DB::table('user_balance_details')
                        ->insert([
                            'type' =>4,
                            'source_income_user_id' => $order->income_user_id,
                            'user_id' => $order->parent_id,
                            'change_type' => 1,
                            'amount' => $order->direct_distribution_income,
                            'remark' => '推广收益',
                            'change_time' => date('Y-m-d H:i:s')
                        ]);

                    event(new Message([
                        'user_id' => $order->parent_id,
                        'type' => 4,
                        'content' => '打赏推广余额收益已入账'
                    ]));
                }


                if ($order->grand_id && $order->direct_distribution_income>0){
                    DB::table('users')
                        ->where('id',$order->grand_id)
                        ->increment('balance',$order->interposition_income);
                    DB::table('user_balance_details')
                        ->insert([
                            'type' =>4,
                            'source_income_user_id' => $order->parent_id,
                            'user_id' => $order->grand_id,
                            'change_type' => 1,
                            'amount' => $order->interposition_income,
                            'remark' => '推广收益',
                            'change_time' => date('Y-m-d H:i:s')
                        ]);

                    event(new Message([
                        'user_id' => $order->grand_id,
                        'type' => 4,
                        'content' => '打赏推广余额收益已入账'
                    ]));
                }


                return Pay::wechat()->success();
            }

        }
    }

    public function aliNotify()
    {
        $config = config('pay');
        Pay::config($config);
        $result = Pay::alipay()->callback()->toArray();
        if ($result['trade_status'] == 'TRADE_SUCCESS') {
            $order = Gift::query()->where('order_no', $result['out_trade_no'])->first();

            if ($order && $order->status == 0) {

                Gift::query()->where('id', $order->id)->update([
                    'status' => 1,
                    'pay_time' => $result['gmt_payment']
                ]);

                DB::table('users')
                    ->where('id', $order->income_user_id)
                    ->increment('balance', $order->user_income);
                DB::table('user_balance_details')
                    ->insert([
                        'type' => 1,
                        'source_income_user_id' => $order->user_id,
                        'user_id' => $order->income_user_id,
                        'change_type' => 1,
                        'amount' => $order->user_income,
                        'remark' => '打赏收益',
                        'change_time' => date('Y-m-d H:i:s')
                    ]);


                event(new \App\Events\Message([
                    'user_id' => $order->user_id,
                    'type' => 3,
                    'content' => '你的打赏已支付成功,资金将会进入您打赏的企业或品牌,感谢您的支持!'
                ]));

                event(new Message([
                    'user_id' => $order->income_user_id,
                    'type' => 4,
                    'content' => '打赏余额收益已入账'
                ]));

                if ($order->parent_id && $order->direct_distribution_income > 0) {
                    DB::table('users')
                        ->where('id', $order->parent_id)
                        ->increment('balance', $order->direct_distribution_income);
                    DB::table('user_balance_details')
                        ->insert([
                            'type' => 4,
                            'source_income_user_id' => $order->income_user_id,
                            'user_id' => $order->parent_id,
                            'change_type' => 1,
                            'amount' => $order->direct_distribution_income,
                            'remark' => '推广收益',
                            'change_time' => date('Y-m-d H:i:s')
                        ]);

                    event(new Message([
                        'user_id' => $order->parent_id,
                        'type' => 4,
                        'content' => '打赏推广余额收益已入账'
                    ]));
                }


                if ($order->grand_id && $order->direct_distribution_income > 0) {
                    DB::table('users')
                        ->where('id', $order->grand_id)
                        ->increment('balance', $order->interposition_income);
                    DB::table('user_balance_details')
                        ->insert([
                            'type' => 4,
                            'source_income_user_id' => $order->parent_id,
                            'user_id' => $order->grand_id,
                            'change_type' => 1,
                            'amount' => $order->interposition_income,
                            'remark' => '推广收益',
                            'change_time' => date('Y-m-d H:i:s')
                        ]);

                    event(new Message([
                        'user_id' => $order->grand_id,
                        'type' => 4,
                        'content' => '打赏推广余额收益已入账'
                    ]));
                }


                return Pay::alipay()->success();

            }
        }
    }
}
